#!/usr/bin/env python
# encoding: utf-8


from app.views.webapi import route_api
from  flask import request,jsonify,g
import requests,json,decimal

from app import app,db
from app.model import Electronic
from app.model import ElectronicLog
from app.model import ElectronicBoom

from app.common.libs.Logging import logger
from app.common.libs.Helper import getFormatDate, stringToDatetime, getCurrentDate
from app.common.libs.ElectronicService import ElectronicService
from app.common.libs.UserService import UserService

from sqlalchemy import func, desc

@route_api.route("/electronic/search",methods = [ "GET","POST" ])
def electronicSearch():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}

    req = request.values
    name = req['name'] if 'name' in req else ''
    sn = req['sn'] if 'sn' in req else ''
    project = req['project'] if 'project' in req else ''
    status = int(req['status']) if 'status' in req else 1

    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    offset = ( page - 1 ) * limit

    query = db.session.query( Electronic )\
        .filter( Electronic.name.like('%'+name+'%'))\
        .filter( Electronic.sn.like('%'+sn+'%'))\
        .filter( Electronic.project.like('%'+project+'%'))\
        .filter( Electronic.status == status )
    # 获取总数
    total = query.count()
    # 获取元器件
    electronic_list = query.order_by(Electronic.name).offset( offset ).limit( limit ).all()

    data_electronic_list = []
    if electronic_list:
        for e in electronic_list:
            image_url =app.config['APP']['domain'] + app.config['UPLOAD_IMAGES']['prefix_path']+str(e.image_url) if e.image_url else ''
            tmp_data = {
                'id':e.id,
                'name':e.name,
                'sn':e.sn,
                'package':e.package,
                'status':e.status,
                'price':str(e.price),
                'spec':e.spec,
                'delivery':e.delivery,
                'stock':e.stock,
                'position':e.position,
                'project':e.project,
                'supplier':e.supplier,
                'image_url':image_url,
            }
            data_electronic_list.append( tmp_data  )

    resp['data']['items'] = data_electronic_list
    resp['data']['total'] = total

    return jsonify( resp )

@route_api.route("/electronic/info",methods = [ "GET","POST" ])
def electronicInfo():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}

    req = request.values
    sn = req['sn'] if 'sn' in req else ''
    if not sn:
        resp['code'] = -1
        resp['message'] = '需要sn'
        return jsonify( resp )

    item = db.session.query(
        Electronic,
        Project.name,
        Product.name,
        Supplier.name)\
        .filter( Electronic.project_id == Project.id )\
        .filter( Electronic.supplier_id == Supplier.id )\
        .filter( Product.project_id == Project.id )\
        .filter( Electronic.status == 1 )\
        .filter( Electronic.sn == sn )\
        .first()
    if not item:
        resp['code'] = -1
        resp['message'] = '设备信息不存在'
        return jsonify( resp )

    electronic = item[0]
    project = item[1]
    product = item[2]
    supplier = item[3]
    resp['data']= {
        'id':electronic.id,
        'name':electronic.name,
        'sn':electronic.sn,
        'package':electronic.package,
        'price':str(electronic.price),
        'stock':electronic.stock,
        'position':electronic.position,
        'created_time':getFormatDate(electronic.created_time),
        'project':project,
        'product':product,
        'supplier':supplier
    }

    return jsonify( resp )

@route_api.route("/electronic/delete/<int:id>",methods = [ "GET","POST" ])
def electronicDelete(id):
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}

    electronic_info = Electronic.query.filter_by( id=id ).first()
    if not electronic_info:
        resp['code'] = -1
        resp['message'] = '设备信息不存在'
        return jsonify( resp )
    electronic_info.status = 2
    #  db.session.delete(electronic_info)
    db.session.commit()
    return jsonify( resp )

@route_api.route("/electronic/edit",methods = [ "GET","POST" ])
def electronicEdit():
    resp = { 'code':20000,'message':'修改成功~', 'data':{}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    electronic_info = Electronic.query.filter_by( id=id ).first()
    if not electronic_info:
        resp['code'] = -1
        resp['message'] = '元器件不存在~'
        return jsonify( resp )

    name     = req['name'] if 'name' in req else ''
    price    = float(req['price'] if 'price' in req else 0)
    stock    = int(req['stock'] if 'stock' in req else 0)
    spec     = req['spec'] if 'spec' in req else ''
    package  = req['package'] if 'package' in req else ''
    position = req['position'] if 'position' in req else ''
    supplier = req['supplier'] if 'supplier' in req else ''
    delivery = req['delivery'] if 'delivery' in req else ''
    project  = req['project'] if 'project' in req else ''
    imageUrl = req['imageUrl'] if 'imageUrl' in req else ''

    electronic_info.name         = name
    electronic_info.package      = package
    electronic_info.price        = decimal.Decimal( price )
    electronic_info.spec         = spec
    electronic_info.stock        = stock
    electronic_info.position     = position
    electronic_info.status       = 1
    electronic_info.supplier     = supplier
    electronic_info.delivery     = delivery
    electronic_info.project      = project
    electronic_info.image_url    = imageUrl
    electronic_info.updated_time = getCurrentDate()
    db.session.commit()
    return jsonify( resp )

@route_api.route("/electronic/add",methods = [ "GET","POST" ])
def electronicAdd():
    resp = { 'code':20000,'message':'添加元器件成功~', 'data':{}}
    req = request.values

    name     = req['name'] if 'name' in req else ''
    price    = float(req['price'] if 'price' in req else 0)
    stock    = int(req['stock'] if 'stock' in req else 0)
    spec     = req['spec'] if 'spec' in req else ''
    package  = req['package'] if 'package' in req else ''
    position = req['position'] if 'position' in req else ''
    delivery = req['delivery'] if 'delivery' in req else ''
    supplier = req['supplier'] if 'supplier' in req else ''
    project  = req['project'] if 'project' in req else ''
    imageUrl  = req['imageUrl'] if 'imageUrl' in req else ''

    electronic_model              = Electronic()
    electronic_model.name         = name
    electronic_model.sn           = ElectronicService.geneSn()
    electronic_model.package      = package
    electronic_model.price        = decimal.Decimal( price )
    electronic_model.spec         = spec
    electronic_model.stock        = stock
    electronic_model.position     = position
    electronic_model.status       = 1
    electronic_model.supplier     = supplier
    electronic_model.delivery     = delivery
    electronic_model.updated_time = electronic_model.created_time = getCurrentDate()
    electronic_model.project      = project
    electronic_model.image_url = imageUrl

    db.session.add( electronic_model )
    db.session.commit()

    # 添加入库记录
    user_info = UserService.getUserInfo(request)
    if not user_info:
        resp['code'] = -1
        resp['message'] = '请重新登录~'
        return jsonify( resp )

    log_model = ElectronicLog()
    log_model.user_id = user_info.id
    log_model.electronic_id = electronic_model.id
    log_model.type = 1 # 入库
    log_model.count = stock
    log_model.note = "新增"
    log_model.created_time = updated_time = getCurrentDate()
    db.session.add( log_model )
    db.session.commit()

    return jsonify( resp )


